package com.xiaocg.sparse.array;

/**
 * 环形队列 记得超过后对数组大小取模
 * @author xiaocg
 */
public class RingQueue {

    private int maxSize;
    private int front=0;
    private int rear=0;
    private int[] arrays;

    public RingQueue(int maxSize) {
        this.maxSize = maxSize;
        arrays = new int[maxSize];
    }

    /**
     * 判断队列是否已满
     */
    public boolean isFull(){
        return (rear+1) % maxSize ==front;
    }

    /**
     * 判断是否为空
     * @return
     */
    public boolean isEmpty(){
        return rear == front;
    }

    /**
     * 添加数据
     * @param n
     */
    public void add(int n){
        if (isFull()){
            System.out.println("队列已满,不能加入数据");
            return;
        }
        arrays[rear] = n;

        rear = (rear+1)%maxSize;
    }

    /**
     * 元素个数
     * @return
     */
    public int count(){
        return (rear-front+maxSize)%maxSize;
    }

    /**
     * 取数据
     * @return
     */
    public int get(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,不能取");
        }
        int array = arrays[front];
        front = (front+1)%maxSize;
        return array;
    }

    /**
     * 打印队列数据
     */
    public void print(){
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }
        for (int i=front;i< front + count();i++){
            System.out.printf("arr[%d]:%d\t",i%maxSize,arrays[i%maxSize]);
        }
    }

    /**
     * 获取头数据
     * @return
     */
    public int getHead(){
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return arrays[front];
    }
}
